//时间格式化
Date.prototype.Format = function (fmt) { //author: meizz
    var o = {
        "M+": this.getMonth() + 1,
        //月份
        "d+": this.getDate(),
        //日
        "h+": this.getHours(),
        //小时
        "m+": this.getMinutes(),
        //分
        "s+": this.getSeconds(),
        //秒
        "q+": Math.floor((this.getMonth() + 3) / 3),
        //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    for (var k in o) {
        if (new RegExp("(" + k + ")").test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        }
    }
    return fmt;
};


//null转空字符串
function NullToBlank(value) {
    if (value == undefined) return "";
    else return value;
}

//==========Ajax请求=============
function doPost(url, data, callback, isAsync) {
    if (!isAsync) {
        $.ajaxSetup({async: false});
    }
    $.post(url, data, callback, 'json').error(function (rst) {
        if (rst.status == 999)
            alert("警告：提交的数据存在敏感信息，你的IP及请求信息已被 记录！");
        else
            alert("本次请求发生错误，错语码：" + rst.status);
    });
    if (!isAsync) {
        $.ajaxSetup({async: true});
    }
}

function doGet(url, data, callback, isAsync) {
    if (!isAsync) {
        $.ajaxSetup({async: false});
    }
    $.get(url, data, callback, 'json').error(function (rst) {
        if (rst.status == 999)
            alert("警告：提交的数据存在敏感信息，你的IP及请求信息已被 记录！");
        else
            alert("本次请求发生错误，错语码：" + rst.status);
    });
    if (!isAsync) {
        $.ajaxSetup({async: true});
    }
}

//异步
function AsyncPost(url, data, callback) {
    doPost(url, data, callback, true);
}

function AsyncGet(url, data, callback) {
    doGet(url, data, callback, true);
}

function SyncPost(url, data, callback) {
    doPost(url, data, callback, false);
}

function SyncGet(url, data, callback) {
    doGet(url, data, callback, false);
}

function Messagebox(msg, title) {
    var $box = $('#MessageBox');
    $box.find('.modal-title').html(title);
    $box.find('.modal-body').html(msg);
    $box.modal();
    return $box;
}

/*function ShowMessage(msg){
	return Messagebox(msg, "提示");
}*/

function ShowMessage(msg, callback) {
    var $box = Messagebox(msg, "提示");
    if (callback != null) {
        $box.find(".modal-footer button").click(function () {
            $box.modal('hide');
            callback();
        })
    }
    return $box;
}

function ErrMessage(msg) {
    return Messagebox(msg, "错误");
}

function DeleteMessage(deleteUrl, data, callback) {
    var $box = $('#delete');
    $box.modal();

    $box.find(".modal-footer button:last").unbind("click").click(function () {
        $box.modal('hide');
        var othis = this;
        $(othis).prop("disabled", true);
        AsyncPost(deleteUrl, data, function (value) {
            if (value.code == 0) {
                ShowMessage("删除成功");
                callback();
            } else {
                ErrMessage(value.msg);
            }
            $(othis).prop("disabled", false);
        })
    })
    return $box;
}


//根据id获取数据并初始化表单
function initFormData(url, data, form) {
    AsyncGet(url, data, function (data) {
        if (data != null) {
            for (var i in data) {
                var key = i.substr(i.indexOf("_") + 1);
                if ($(form).find("[name='" + key + "']").is("input:text,input:password,input:hidden")) {
                    $(form).find("[name='" + key + "']").val(data[i]);
                }
                if ($(form).find("[name='" + key + "']").is("span")) {
                    $(form).find("[name='" + key + "']").text(data[i]);
                }
                if ($(form).find("[name='" + key + "']").is("select")) {
                    if (data[i] != null) {
                        if ($(form).find("[name='" + key + "']").parent().find("select").length != 1) {
                            var value = data[i] + "";
                            var length = $(form).find("[name='" + key + "']").parent().find("select").length;
                            for (var j = 0; j < length; j++) {
                                var select = $(form).find("[name='" + key + "']").parent().find("select:eq(" + j + ")");
                                var string = $(select).find("option:last").val() + "";
                                $(select).val(value.substr(0, string.length)).change();
                            }
                        } else {
                            $(form).find("[name='" + key + "']").val(data[i]).change();
                        }
                    }
                }
                if ($(form).find("[name='" + key + "']").is("textarea")) {
                    $(form).find("[name='" + key + "']").val(data[i]);
                }
            }
        }
    });
}

function getFormData(form) {
    var data = {};
    $(form).find("input[name],select[name]").each(function (index, value) {
        data[$(this).attr("name")] = $(this).val();
    });
    return data;
}

function getFileFormData(form) {
    var formData = new FormData();
    $(form).find("input[name],select[name]").each(function (index, value) {
        if ($(this).is("[type='file']")) {
            formData.append($(this).attr("name"), this.files[0]);
        } else {
            formData.append($(this).attr("name"), $(this).val());
        }

    });
    return formData;
}

function clearFormData(form) {
    $(form).find("input[name],select[name]").each(function () {
        $(this).val("");
    })
}

//根据ID初始化下拉框
function loadSelectById(url, code, id) {
    SyncPost(url, code, function (data) {
        $("#" + id).empty().append("<option value>--请选择--</option>");
        for (var i = 0; i < data.length; i++) {
            var option = $("<option></option>");
            $(option).attr("value", data[i].code);
            $(option).text(data[i].name);
            $("#" + id).append(option);
        }
        $("#" + id).val("");
    });
}

//根据ID初始化下拉框
function loadSelectByIdAsync(url, code, id) {
    AsyncPost(url, code, function (data) {
        $("#" + id).empty().append("<option value>--请选择--</option>");
        for (var i = 0; i < data.length; i++) {
            var option = $("<option></option>");
            $(option).attr("value", data[i].code);
            $(option).text(data[i].name);
            $("#" + id).append(option);
        }
        $("#" + id).val("");
    });
}

//根据class初始化下拉框
function loadSelectByClass(url, code, className) {
    AsyncPost(url, code, function (data) {
        $("." + className).empty().append("<option value>--请选择--</option>");
        for (var i = 0; i < data.length; i++) {
            var option = $("<option></option>");
            $(option).attr("value", data[i].code);
            $(option).text(data[i].name);
            $("." + className).append(option);
        }
        $("." + className).val("");
    });
}

//根据name初始化下拉框
function loadSelectByName(url, code, name) {
    SyncPost(url, code, function (data) {
        $("[name=" + name + "]").empty().append("<option value>--请选择--</option>");
        for (var i = 0; i < data.length; i++) {
            var option = $("<option></option>");
            $(option).attr("value", data[i].code);
            $(option).text(data[i].name);
            $("[name=" + name + "]").append(option);
        }
        $("[name=" + name + "]").val("");
    });
}

//根据url，参数data初始化table中的数据
function initTable(url, searchId, table, pagingClass) {

    var object = new Object();
    var getDataBySearchId = function () {
        var param = {};
        $("#" + searchId).find("input[name],select[name]").each(function (index, value) {
            param[$(this).attr("name")] = $(this).val();
        });
        param['size'] = $("#" + searchId).find(".page .page_active").text();
        return param;
    }
    var changeFunction = function () {
        $("#" + searchId).find("input[name],select[name]").change(function () {
            $("." + pagingClass + " a.active").removeClass("active");
            search();
        })
        $("#" + searchId).find(".btn-search").click(function () {
            $("." + pagingClass + " a.active").removeClass("active");
            search();
        })
        $("#" + searchId).find(".page span").click(function () {
            $("." + pagingClass + " a.active").removeClass("active");
            search();
        })
    }
    var search = function () {
        var param = getDataBySearchId();
        AsyncGet(url, param, function (totalPage) {
            startPage(pagingClass, totalPage, function (page) {
                param['page'] = page - 1;
                AsyncPost(url, param, function (value) {
                    $(table).find("tbody").empty();
                    for (var i = 0; i < value.length; i++) {
                        var tr = "<tr>";
                        $(table).find("thead th").each(function () {
                            if ($.trim($(this).attr("name")) == "") {
                                tr += "<td>" +
                                    "<a class='fa fa-edit' title='编辑' style='font-size:20px;cursor:pointer;color:#235F8F'></a>" +
                                    "<a class='fa fa-trash-o' title='删除' style='font-size:20px;cursor:pointer;color:#235F8F'></a>" +
                                    "</td>";
                            } else if ($(this).is(":hidden")) {
                                tr += "<td style='display:none;'>" + NullToBlank(value[i][$(this).attr("name")]) + "</td>";
                            } else {
                                tr += "<td >" + NullToBlank(value[i][$(this).attr("name")]) + "</td>";
                            }
                        })
                        tr += "</tr>";
                        $(table).find("tbody").append(tr);
                    }

                })
            }, 5, ErrMessage);
        })
    }
    search();
    changeFunction();
    object.search = search;
    return object;
}

function EditEntity(editTitle, addTitle, table, addButton, htmlUrl, getEntityUrl, updateEntityUrl, deleteEntityUrl, callback) {
    var $box = $('#EditEntity');
    if (htmlUrl != null) {
        $box.find('.modal-body').load(htmlUrl);
    }

    if (deleteEntityUrl != null) {
        $(table).on("click", "tbody td a:last-child", function () {
            DeleteMessage(deleteEntityUrl, {id: $(this).parents("tr").find("td:first").text()}, callback);
        })
    }

    if (getEntityUrl != null) {
        $(table).on("click", "tbody td a:first-child", function () {
            $box.modal("show");
            $box.find('.modal-title').text(editTitle);
            $box.find('[onlyread]').prop("disabled", true);
            $box.find('[updateonlyread]').prop("disabled", true);
            $box.find('[addonlyread]').prop("disabled", false);
            initFormData(getEntityUrl, {id: $(this).parents("tr").find("td:first").text()}, $box.find(".modal-body form"));
        })
    }

    if (addButton != null) {
        $(addButton).click(function () {
            $box.modal("show");
            $box.find('.modal-title').text(addTitle);
            $box.find('[onlyread]').prop("disabled", true);
            $box.find('[updateonlyread]').prop("disabled", false);
            $box.find('[addonlyread]').prop("disabled", true);
            clearFormData($box.find(".modal-body form"));
        })
    }


    if (updateEntityUrl != null) {
        $box.find(".modal-footer button:last").click(function () {
            AsyncPost(updateEntityUrl, getFormData($box.find(".modal-body form")), function (value) {
                if (value.code == 0) {
                    ShowMessage(value.msg);
                    $box.modal("hide");
                    callback();
                } else {
                    ErrMessage(value.msg);
                }
            })
        })
    }
}

function getDay(day) {
    switch (day) {
        case 1:
            return "星期一";
        case 2:
            return "星期二";
        case 3:
            return "星期三";
        case 4:
            return "星期四";
        case 5:
            return "星期五";
        case 6:
            return "星期六";
        default:
            return "星期天";
    }
}

